﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Raspare;
using Xamarin.Forms;

namespace SharedMobilePlatform
{
	public class KrokarPage : RaspContentPage
	{

        public ProgressBar progressBar;

        private Label krokar;
	    private string name;
        private List<Kroklista> krokarLista = new List<Kroklista>();

        public KrokarPage(string characterName)
		{
            Title = "Krokar";
            name = characterName;

            if (Application.Current.Properties.ContainsKey("Kroklista") && Application.Current.Properties["Kroklista"] != null)
            {
                krokarLista = Application.Current.Properties["Kroklista"] as List<Kroklista>;
                PrintKrokar();
            }

            progressBar = new ProgressBar() { Progress = 0.2 };
            krokar = new Label() { Text = "", FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)) };
            var scrollview = new ScrollView
            {
                Content = new StackLayout
                {
                    Children = {
                        progressBar,
					    new Label { Text = "Krokar i kampanjen", FontSize = Device.GetNamedSize (NamedSize.Large, typeof(Label))},
                        krokar
				    }
                }
            };
            Content = scrollview;
            
            progressBar.ProgressTo(.8, 5000, Easing.Linear);
            _client.GetKrokarAsync(characterName);

		}

	    public override void InitializeWcfServiceClient()
	    {
            _client.GetKrokarCompleted += GetKrokarCompleted;
	    }

        private void GetKrokarCompleted(object sender, GetKrokarCompletedEventArgs e)
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                progressBar.IsVisible = false;
                if (!e.Cancelled)
                {
                    if (String.IsNullOrWhiteSpace(name)) return;
                    try { 
                        krokarLista = e.Result.ToList();
                        PrintKrokar();
                    }
                    catch (TargetInvocationException)
                    {
                        DisplayAlert("Får ingen kontakt med servern", "Servern svarar inte just nu, försök igen senare. Kroklistan uppdaterades inte.", "OK");
                    }
                }
            });
        }

	    private void PrintKrokar()
	    {
            string text = string.Empty;
            foreach (var krokLista in krokarLista)
            {
                text += krokLista.Namn + ":" + System.Environment.NewLine;
                foreach (var krok in krokLista.Krokar)
                {
                    text += " - " + krok + System.Environment.NewLine;
                }
                text += System.Environment.NewLine;
            }
            krokar.Text = text;
	    }
	}
}
